package com.sav.common.controller;
 

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sav.common.catalog.Product;
import com.sav.common.containers.ContentContainer;
import com.sav.common.dao.ProductDAO;
import com.sav.common.localCatalog.Catalog;
import com.sav.common.localCatalog.LocalCategory;

    
@Controller
public class MainController { 
    
    @Autowired(required = true)
    private ProductDAO productDAO;
     
    @RequestMapping(value = "/main", method = RequestMethod.GET) 
    public String mainMethod(ModelMap model) throws Exception {
    	List<LocalCategory> listParentCategory = Catalog.getInstance().getListParentCategory();
		model.addAttribute(
				"parentCategory", 
				Catalog.listLocalCategoriesToListCategories(listParentCategory));
        return "main"; 
    }
    
    
    @RequestMapping(value = "/getSubcategory", method = RequestMethod.POST)
    public @ResponseBody ContentContainer getSubcategory(@RequestParam(value="id", required=true) Integer id,
           Model model)  throws Exception{
    	
    	List<LocalCategory> listSubCategory = Catalog.getInstance().getListSubCategory(id);
    	ContentContainer container = new ContentContainer(
    			Catalog.listLocalCategoriesToListCategories(listSubCategory), 
    			Catalog.getInstance().getCountProductsInCategory(id));
    	
    	return container;
	}
    
    
    @RequestMapping(value = "/getProducts", method = RequestMethod.POST)
    public @ResponseBody List<Product> getProducts(
    		@RequestParam(value = "id", required = true) Integer idCategory,
    		@RequestParam(value = "curPage", required = true) Integer cPage,
    		Model model)  throws Exception{

    	int first = Consts.COUNT_PRODUCT_ON_PAGE*(cPage - 1);
    	return productDAO.getListProductsByCategory(idCategory, first, Consts.COUNT_PRODUCT_ON_PAGE);
	}
}